﻿using Entity;
using IService;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;

namespace XingWeDaWMSProject.Controllers
{
    public class NumberingRuleController : Controller
    {
        private readonly INumberingRuleService _numberingRuleService;
        private readonly ITargetFormService _targetFormService;

        public NumberingRuleController(INumberingRuleService numberingRuleService, ITargetFormService targetFormService)
        {
            _numberingRuleService = numberingRuleService ?? throw new ArgumentNullException(nameof(numberingRuleService));
            _targetFormService = targetFormService ?? throw new ArgumentNullException(nameof(targetFormService));
        }

        /// <summary>
        /// 显示编号规则列表页
        /// </summary>
        public IActionResult Index()
        {
            try
            {
                var rules = _numberingRuleService.QueryByConditions(new NumberingRuleQueryParams()) ?? new List<NumberingRule>();

                foreach (var rule in rules)
                {
                    rule.SerialNumber = rule.SerialNumber > 0 ? rule.SerialNumber : 0;
                    rule.Step = rule.Step > 0 ? rule.Step : 1;
                    rule.TimeRule = rule.TimeRule ?? string.Empty;
                    rule.NumberProductionRule = rule.NumberProductionRule ?? string.Empty;
                    rule.OperationTime = DateTime.Now;
                }

                var targetForms = _targetFormService.GetAll() ?? new List<TargetForm>();
                // 手动构造SelectListItem列表
                List<SelectListItem> targetFormItems = new List<SelectListItem>();
                foreach (var form in targetForms)
                {
                    targetFormItems.Add(new SelectListItem
                    {
                        Value = form.TargetID.ToString(), // 假设TargetID是int类型，转为字符串
                        Text = form.targetForm // 假设FormName是目标表单名称属性
                    });
                }
                ViewBag.TargetForms = targetFormItems;

                return PartialView(rules);
            }
            catch (Exception ex)
            {
                return PartialView("Error", new { Message = $"加载列表失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 处理查询请求（AJAX）
        /// </summary>
        [HttpPost]
        public IActionResult Query(NumberingRuleQueryParams queryParams)
        {
            try
            {
                var rules = _numberingRuleService.QueryByConditions(queryParams)
                          ?? new List<NumberingRule>();

                // 处理空值
                foreach (var rule in rules)
                {
                    rule.SerialNumber = rule.SerialNumber > 0 ? rule.SerialNumber : 0;
                    rule.Step = rule.Step > 0 ? rule.Step : 1;
                }

                return Json(new { success = true, data = rules });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, error = ex.Message });
            }
        }

        /// <summary>
        /// 显示编辑页
        /// </summary>
        public IActionResult Edit(int? ruleId)
        {
            var rule = new NumberingRule();
            try
            {
                if (ruleId.HasValue)
                {
                    rule = _numberingRuleService.GetById(ruleId.Value)
                          ?? throw new KeyNotFoundException("未找到指定的编号规则");
                }
                else
                {
                    // 编辑页不支持新增，仅保留编辑功能
                    return RedirectToAction("Index");
                }

                // 确保编辑页数据完整性
                rule.Step = rule.Step > 0 ? rule.Step : 1;
                rule.SerialNumber = rule.SerialNumber > 0 ? rule.SerialNumber : 3;

                // 传递目标表单列表
                var targetForms = _targetFormService.GetAll() ?? new List<TargetForm>();
                ViewBag.TargetForms = new Microsoft.AspNetCore.Mvc.Rendering.SelectList(
                    targetForms, "TargetID", "FormName", rule.TargetID);

                return View(rule);
            }
            catch (Exception ex)
            {
                return View("Error", new { Message = $"加载表单失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 保存编号规则
        /// </summary>
        [HttpPost]
        public IActionResult Save(NumberingRule rule)
        {
            try
            {
                // 验证模型
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Values
                        .SelectMany(v => v.Errors)
                        .Select(e => e.ErrorMessage);
                    return Json(new { success = false, message = string.Join("; ", errors) });
                }

                // 仅允许编辑（不允许新增）
                if (rule.RuleID <= 0)
                {
                    return Json(new { success = false, message = "不支持新增规则" });
                }

                // 获取当前用户
                var currentUser = User.FindFirstValue(ClaimTypes.Name) ?? "system";
                rule.Operator = currentUser;

                // 保存规则
                var result = _numberingRuleService.SaveRule(rule);
                return Json(new { success = true, message = "保存成功", ruleId = result });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }
        public IActionResult EditPartial(int ruleId)
        {
            var rule = _numberingRuleService.GetById(ruleId);
            if (rule == null)
            {
                return NotFound();
            }
            return PartialView(rule);
        }
    }
}
